/*
 * @Author: tomystery 
 * @Date: 2018-05-14 09:59:33 
 * @Last Modified by: t
 * @Last Modified time: 2018-05-15 14:16:14
 */
import React from 'react'
import MUtil from 'util/mm.jsx'
import User from 'service/user-service.jsx'
const _mm = new MUtil()
import './index.scss'

const _user = new User()

class Login extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            username: '',
            password: '',
            redirect: _mm.getUrlParam('redirect') || '/'
        }

    }
    componentWillMount() {
        document.title = '登陆-MMALL ADMIN'
    }

    onInputChange(e) { //通过一个事件处理全部的输入
        let inputName = e.target.name
        let inputValue = e.target.value
        this.setState({
            [inputName]: inputValue
        })
    }

    onInputKeyUp(e){
        if(e.keyCode===13){
            this.onSubmit()
        }
    }

    //用户提交表单
    onSubmit() {
        let loginInfo = {
            username: this.state.username,
            password: this.state.password
        }

        //验证提交数据
        let checkResult = _user.checkLoginInfo(loginInfo);
        if (checkResult.status) {
            _user.login(loginInfo).then((res) => {
                //把用户信息存到本地
                _mm.setStorage('userInfo',res);
               
                //返回到他的前一步
                this.props.history.push(this.state.redirect);
            }, (err) => {
                //错误提示框
                _mm.errTips(err)

            })
        } else {
            _mm.errTips(checkResult.msg)
        }

    }

    render() {
        return (
            <div className='col-md-4 col-md-offset-4'>
                <div className="panel panel-default login-panel">
                    <div className="panel-heading">欢迎登陆MMALL管理系统</div>
                    <div className="panel-body">
                        <div>
                            <div className="form-group">

                                <input type="text" className="form-control" name='username' onKeyUp={(e)=>this.onInputKeyUp(e)} placeholder="请输入用户名"
                                    onChange={(e) => this.onInputChange(e)} />
                            </div>
                            <div className="form-group">

                                <input type="password" className="form-control" name='password' onKeyUp={(e)=>this.onInputKeyUp(e)} placeholder="请输入密码"
                                    onChange={(e) => this.onInputChange(e)} />
                            </div>
                            <button className="btn btn-primary btn-lg btn-block"  onClick={(e) => this.onSubmit()}>登陆</button>
                        </div>
                    </div>
                </div>
            </div>


        )
    }
}

export default Login